#!/usr/bin/env node

const fs   = require('fs'),
      path = require('path');
      cmd  = process.argv[2],
      name = process.argv[3],
      list = [];
      log  = console.log;

const files = fs.readdirSync('./sysFile');

const compare = (prop)=>{
  return (a,b)=>{
    let value1 = a[prop];
    let value2 = b[prop];
    return value1-value2;
  }
};

const remove = (fn)=>{
  let list = fs.readdirSync(fn);
  list.forEach((item)=>{
    let fp = path.join(fn,item);
    if(fs.statSync(fp).isFile()){
      log(path.basename(fp)+"删除成功");
      fs.unlinkSync(fp,(err)=>{
        if(err){
          log('文件不存在');
          process.exit();
        }      
      })
    }else{
      return remove(fp);
    }
  });
  fs.rmdirSync(fn);
  log(path.basename(fn)+ "删除成功");
}



if(cmd==="-list"){
  files.forEach((item)=>{
    if(fs.statSync('./sysFile/'+item).isFile()){
      let fileName = item;
      let fileSize = fs.statSync('./sysFile/'+item).size;
      list.push({
        fileName:fileName,
        fileSize:fileSize
      });

    }
  })
  list = list.sort(compare('fileSize'));
  log(JSON.stringify(list));
}else if(cmd==='-show'){
  fs.readFile(name,(err,data)=>{
    if(err){
      log('文件不存在');
      process.exit();
    }
    log(data.toString('utf8'));
  })
}else if(cmd==='-del'){
  if(fs.statSync(name).isFile()){
    log(path.base(name)+ "删除成功")
    fs.unlinkSync(name,(err)=>{
      if(err){
        log('文件不存在');
        process.exit();
      }      
    })
  };
  if(fs.statSync(name).isDirectory()){
    remove(name);
  }
}


